package com.vision.sales.salesinvoice.cl.ui;

import static com.vision.sales.cl.SalesServices.salesInvoiceSvc;

import java.util.Date;
import java.util.HashSet;

import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.Editor;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiFactory;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.widget.core.client.Window;
import com.sencha.gxt.widget.core.client.button.TextButton;
import com.sencha.gxt.widget.core.client.event.HideEvent;
import com.sencha.gxt.widget.core.client.event.SelectEvent;
import com.sencha.gxt.widget.core.client.form.DateField;
import com.sencha.gxt.widget.core.client.form.NumberField;
import com.sencha.gxt.widget.core.client.form.NumberPropertyEditor;
import com.sencha.gxt.widget.core.client.form.SimpleComboBox;
import com.sencha.gxt.widget.core.client.form.TextArea;
import com.sencha.gxt.widget.core.client.form.TextField;
import com.sencha.gxt.widget.core.client.form.validator.MaxLengthValidator;
import com.vision.core.cl.BaseModule;
import com.vision.core.cl.Callback;
import com.vision.core.cl.ui.ConfirmDialogHandler;
import com.vision.core.cl.ui.UI;
import com.vision.core.cl.ui.component.CompanyComboBox;
import com.vision.core.cl.ui.component.CompanyGroupComboBox;
import com.vision.core.cl.ui.component.EnumComboBox;
import com.vision.core.cm.db.data.CompanyGroup;
import com.vision.sales.cl.event.SalesInvoiceCreatedEvent;
import com.vision.sales.cl.resource.SalesResources;
import com.vision.sales.cl.ui.component.CustomerComboBox;
import com.vision.sales.cl.ui.component.ProductComboBox;
import com.vision.sales.cm.data.CollectionStatus;
import com.vision.sales.cm.db.data.Customer;
import com.vision.sales.cm.db.data.DeliveryReceipt;
import com.vision.sales.cm.db.data.SalesInvoice;
import com.vision.sales.cm.db.data.SalesInvoice.FieldSpecs;

/**
 * Used for creating new {@link SalesInvoice}s without {@link DeliveryReceipt}s.
 * 
 * @author Mark
 *
 */
public class CreateSalesInvoiceWindow implements IsWidget, Editor<SalesInvoice> {
	
	interface Binder extends UiBinder<Widget, CreateSalesInvoiceWindow> { }
	
	private static final Binder binder = GWT.create(Binder.class);
	
	@UiField Window window;
	
	// Form fields that are bound by the form driver to the fields in the Customer class.
	// The name of these form fields must match the name of the field in the Customer class. 
	@UiField CompanyComboBox company;
	@UiField CompanyGroupComboBox group;
	@UiField TextField invoiceNo;
	@UiField DateField date;
	@UiField TextField poNo;
	@UiField CustomerComboBox customer;
	@Ignore @UiField TextField salesmanTxt;
	
	@Ignore @UiField(provided = true) NumberPropertyEditor<Double> doublePropertyEditor = UI.doubleEditor();
	@Ignore @UiField(provided = true) NumberFormat numberFormat = UI.amountFormat();
	@UiField NumberField<Double> grossSales;
	
	@UiField ProductComboBox product;
	
	@UiField TextArea remarks;
	@UiField TextArea itemsDelivered;
	
	@Ignore @UiField TextButton saveBtn;
	@Ignore @UiField TextButton cancelBtn;
	
	interface SalesInvoiceDriver extends SimpleBeanEditorDriver<SalesInvoice, CreateSalesInvoiceWindow> { }
	
	private SalesInvoiceDriver driver = GWT.create(SalesInvoiceDriver.class);
	
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	
	public CreateSalesInvoiceWindow() {
	}
	
	@Override
	public Widget asWidget() {
		window = (Window) binder.createAndBindUi(this);
		window.getHeader().setIcon(SalesResources.INSTANCE.salesInvoices());
		
		driver.initialize(this);
		driver.edit(new SalesInvoice(new Date()));
		
		date.setPropertyEditor(UI.datePropertyEditor());
		date.setValue(new Date());
		
		invoiceNo.addValidator(new MaxLengthValidator(FieldSpecs.INVOICE_NO_MAX));
		poNo.addValidator(new MaxLengthValidator(FieldSpecs.PO_NO_MAX));
		itemsDelivered.addValidator(new MaxLengthValidator(FieldSpecs.ITEMS_DELIVERED_MAX));
		remarks.addValidator(new MaxLengthValidator(FieldSpecs.REMARKS_MAX));
		
		loadData();
		
		return window;
	}
	
	// UiFactory Methods %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	
	@Ignore
	@UiFactory
	SimpleComboBox<CollectionStatus> initializeCollectionStatusCombo() {
		return new EnumComboBox<CollectionStatus>(CollectionStatus.values());
	}
	
	// UiHandlers %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

	@UiHandler("group")
	void groupChanged(SelectionEvent<CompanyGroup> e) {
		CompanyGroup group = e.getSelectedItem();
		company.setValue(group.getCompany());
	}
	
	@UiHandler("customer")
	void customerChanged(SelectionEvent<Customer> e) {
		Customer customer = e.getSelectedItem();
		if (customer != null) {
			salesmanTxt.setText(customer.getSalesman() == null ? "" : customer.getSalesman().getCode());
		}
	}
	
	@UiHandler("saveBtn")
	void saveClicked(SelectEvent e) {
		final SalesInvoice invoice = driver.flush();
		if (driver.hasErrors())
			return;
		
		invoice.setCompany(invoice.getGroup().getCompany());
		
		if (invoice.getGrossSales() == 0D) {
			UI.confirm("Zero Gross Sales", "The gross sales amount is zero. Do you wish to continue?", new ConfirmDialogHandler() {
				@Override
				public void onYes(HideEvent event) {
					doTheSave(invoice);
				}
			});
		} else {
			doTheSave(invoice);
		}
	}
	
	@UiHandler("cancelBtn")
	void cancelClicked(SelectEvent e) {
		window.hide(cancelBtn);
	}
	
	// Logic %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

	public void loadData() {
		Log.debug("Loading salesmen, companies, customers, products for dropdown...");
		
		UI.mask(company, "Loading companies...");
		company.loadCompanies();
		
		UI.mask(group, "Loading groups...");
		group.loadGroups();
		
		UI.mask(customer, "Loading customers...");
		customer.loadCustomers();
		
		UI.mask(product, "Loading products...");
		product.loadProducts();
	}
	
	void doTheSave(final SalesInvoice invoice) {
		invoice.setCollectionStatus(CollectionStatus.UNPAID);
		
		invoice.setSalesman(invoice.getCustomer().getSalesman());
		invoice.setDeliveryReceipts(new HashSet<DeliveryReceipt>());
		
		UI.mask(window, "Creating sales invoice...");
		salesInvoiceSvc().create(invoice, new Callback<SalesInvoice>(window) {
			@Override
			protected void handleSuccess(SalesInvoice result) {
				window.hide(saveBtn);
				BaseModule.fireEvent(new SalesInvoiceCreatedEvent(result));
			}
		});
	}

}
